package com.wufun.overseas.view;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.wufun.overseas.R;
import com.wufun.overseas.utils.IntentUtil;


/**
 * Created by xiet on 2015/11/9.
 */
public class ForumLoadingView extends RelativeLayout {
    private Context mContext;
    private View loadingMainV;
    private View loadingFailedMainV;
    private ImageView loadingFailedReloadingV;
    private TextView loadingFailedMsgV;
    private View loadingFailedDividerV;
    private Button loadingFailedImgV;

    public static final int LOADING = 0x01;
    public static final int LOADING_SUCCESS = LOADING << 1;
    public static final int LOADING_FAILED = LOADING << 2;
    public static final int LOADING_FAILED_NETWORK = (LOADING << 3) + 0x01;
    public static final int LOADING_FAILED_NO_REC = (LOADING << 3) + (0x01 << 1);
    public static final int LOADING_FAILED_OTHERS = LOADING << 4;
    protected int loadingState = LOADING;

    private Handler mHandler;

    enum HandleId {
        LOADING,
        LOADING_SUCCESS,
        LOADING_FAILED,
        SET_RELOADING_VISIBILITY,
        SET_FAILED_IMG_VISIBILITY,
        SET_FAILED_IMG_RES,
        SET_FAILED_RELOADING_RES,
        SET_FAILED_MSG
    }

    public ForumLoadingView(Context context) {
        super(context);
        initWithContext(context);
    }

    public ForumLoadingView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initWithContext(context);
    }

    public ForumLoadingView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initWithContext(context);
    }

    private void initWithContext(Context context) {
        this.mContext = context;
        //get views
        View loadingView = LayoutInflater.from(context).inflate(R.layout.loding_layout_include, null);
        loadingMainV = loadingView.findViewById(R.id.loding_layout);

        View loadingFailedView = LayoutInflater.from(context).inflate(R.layout.failed_layout_include, null);
        loadingFailedMainV = loadingFailedView.findViewById(R.id.loding_faile);
        loadingFailedReloadingV = (ImageView) loadingFailedView.findViewById(R.id.relodingimag);
        loadingFailedMsgV = (TextView) loadingFailedView.findViewById(R.id.failedMessage);
        loadingFailedDividerV = loadingFailedView.findViewById(R.id.lodingBackImage);
        loadingFailedImgV = (Button) loadingFailedView.findViewById(R.id.setNetwork);

        //add to root
        addView(loadingView);
        addView(loadingFailedView);
        LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        loadingView.setLayoutParams(params);
        loadingFailedView.setLayoutParams(params);

        //set attr
        loadingMainV.setVisibility(View.GONE);
        loadingFailedMainV.setVisibility(View.GONE);
        loadingFailedImgV.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                IntentUtil.getInstance().goWirelessSettings(v.getContext());
            }
        });
        loadingFailedReloadingV.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mListener != null) mListener.onReloading();
            }
        });
        loadingFailedImgV.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mListener != null) mListener.onEvent(v);
            }
        });

        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                try {

                    int id = msg.what;

                    if (id == HandleId.LOADING.ordinal()) {
                        showLoading();
                    } else if (id == HandleId.LOADING_FAILED.ordinal()) {
                        showLoadingFailed();
                    } else if (id == HandleId.LOADING_SUCCESS.ordinal()) {
                        showMain(true);
                    } else if (id == HandleId.SET_FAILED_IMG_VISIBILITY.ordinal()) {
                        int visibility = msg.arg1;
                        setFailedImgVisibilityP(visibility);
                    } else if (id == HandleId.SET_RELOADING_VISIBILITY.ordinal()) {
                        int visibility = msg.arg1;
                        setReloadingVisibilityP(visibility);
                    } else if (id == HandleId.SET_FAILED_IMG_RES.ordinal()) {
                        setFailedImgResP(msg.arg1);
                    } else if (id == HandleId.SET_FAILED_RELOADING_RES.ordinal()) {
                        setFailedReloadingResP(msg.arg1);
                    }  else if (id == HandleId.SET_FAILED_MSG.ordinal()) {
                        String s = (String) msg.obj;
                        setFailedMsgP(s);
                    }

                    invalidate();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
    }

    private void showLoading() {
        loadingMainV.setVisibility(View.VISIBLE);
        loadingFailedMainV.setVisibility(View.GONE);
        showMain(false);
    }

    private void showLoadingFailed() {
        loadingMainV.setVisibility(View.GONE);
        loadingFailedMainV.setVisibility(View.VISIBLE);
        showMain(false);
    }

    private void showMain(boolean show) {
        int visibility = View.VISIBLE;
        if (!show) {
            visibility = View.GONE;
        }

        for (int i = 0; i < getChildCount(); i++) {
            View child = getChildAt(i);
            if (child == loadingMainV || child == loadingFailedMainV) {
                if (show) {
                    child.setVisibility(View.GONE);
                }
                continue;
            }
            child.setVisibility(visibility);
        }
        if (mListener != null) mListener.onShow(show);
    }

    private void setFailedMsgP(String msg) {
        if (loadingFailedMsgV != null) loadingFailedMsgV.setText(msg);
    }

    private void setFailedImgResP(int resId) {
        try {
            if (resId == LOADING_FAILED_NETWORK) {
//                loadingFailedImgV.setText(getResources().getString(R.string.set_net));
            } else if (resId == LOADING_FAILED_NO_REC) {
                loadingFailedImgV.setText(getResources().getString(R.string.forum_post_more));
            } else {
                loadingFailedImgV.setText("");
                loadingFailedImgV.setBackgroundResource(resId);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void setFailedReloadingResP(int resId) {
        try {
            loadingFailedReloadingV.setImageResource(resId);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void setFailedImgVisibilityP(int visibility) {
        int visible = View.GONE;
        if (visibility == View.VISIBLE) visible = View.VISIBLE;
        loadingFailedDividerV.setVisibility(visible);
        loadingFailedImgV.setVisibility(visible);
    }

    private void setReloadingVisibilityP(int visibility) {
        int visible = View.VISIBLE;
        if (visibility == View.GONE) visible = View.GONE;
        loadingFailedReloadingV.setVisibility(visible);
    }

    public void setFailedImgVisibility(int visibility) {
        Message message = mHandler.obtainMessage();
        message.what = HandleId.SET_FAILED_IMG_VISIBILITY.ordinal();
        message.arg1 = visibility;
        message.sendToTarget();
    }

    public void setReloadingVisibility(int visibility) {
        Message message = mHandler.obtainMessage();
        message.what = HandleId.SET_RELOADING_VISIBILITY.ordinal();
        message.arg1 = visibility;
        message.sendToTarget();
    }

    public void setFailedImgRes(int resId) {
        Message message = mHandler.obtainMessage();
        message.what = HandleId.SET_FAILED_IMG_RES.ordinal();
        message.arg1 = resId;
        message.sendToTarget();
    }

    public void setFailedReloadingRes(int resId) {
        Message message = mHandler.obtainMessage();
        message.what = HandleId.SET_FAILED_RELOADING_RES.ordinal();
        message.arg1 = resId;
        message.sendToTarget();
    }

    public void setFailedMsg(String msg) {
        Message message = mHandler.obtainMessage();
        message.what = HandleId.SET_FAILED_MSG.ordinal();
        message.obj = msg;
        message.sendToTarget();
    }

    public void change(int state) {

        setFailedImgVisibility(View.VISIBLE);
        setReloadingVisibility(View.VISIBLE);

        if (loadingState == LOADING_SUCCESS) {
            return;
        } else if (state == LOADING_SUCCESS) {
            loadingState = LOADING_SUCCESS;
        } else if (state == LOADING) {
            loadingState = LOADING;
        } else if (state == LOADING_FAILED_NETWORK) {
            loadingState = LOADING_FAILED_NETWORK;
            setFailedMsg(getResources().getString(R.string.network_failed));
            setFailedImgRes(LOADING_FAILED_NETWORK);
        } else if (state == LOADING_FAILED_NO_REC) {
            loadingState = LOADING_FAILED_NO_REC;
            setReloadingVisibility(View.GONE);
            setFailedImgRes(LOADING_FAILED_NO_REC);
        } else {
            if ((state & LOADING_FAILED_OTHERS) == LOADING_FAILED_OTHERS) {
                loadingState |= state;
            } else {
                loadingState |= state;
            }
            setFailedMsg(getResources().getString(R.string.forum_load_failed));
            setFailedImgVisibility(View.GONE);
        }

        int loadingViewState = 0;
        if (loadingState == LOADING) {
            loadingViewState = LOADING;
        } else if (loadingState == LOADING_SUCCESS) {
            loadingViewState = LOADING_SUCCESS;
        } else {
            loadingViewState = LOADING_FAILED;
        }
        Message msg = mHandler.obtainMessage();
        switch (loadingViewState) {
            case LOADING:
                msg.what = HandleId.LOADING.ordinal();
                break;
            case LOADING_FAILED:
                msg.what = HandleId.LOADING_FAILED.ordinal();
                break;
            case LOADING_SUCCESS:
                msg.what = HandleId.LOADING_SUCCESS.ordinal();
                break;
        }
        msg.sendToTarget();
    }

    public void reset() {
        if (loadingState != LOADING) {
            loadingState = LOADING;
        }
    }

    public boolean isSuccess() {
        return loadingState == LOADING_SUCCESS;
    }

    public int getLoadingState() {
        return loadingState;
    }

    //view listener
    private ForumLoadingStateListener mListener;

    public void setListener(ForumLoadingStateListener l) {
        this.mListener = l;
    }

    public abstract static class ForumLoadingStateListener {
        ForumLoadingView loadingView;
        public ForumLoadingStateListener(ForumLoadingView loadingView) {
            this.loadingView = loadingView;
        }

        public void onShow(boolean show) {
        }

        public void onReloading() {
        }

        public void onEvent(View v) {
            Context context = v.getContext();
            if (loadingView.getLoadingState() == LOADING_FAILED_NETWORK) {
                IntentUtil.getInstance().goWirelessSettings(context);
            } else if (loadingView.getLoadingState() == LOADING_FAILED_NO_REC) {
//                ForumUtil.goForumWelcomeFragment(context);


            }
        }
    }

}
